//
//  ViewController.swift
//  ContactListDemo
//
//  Created by dengwei on 16/5/30.
//  Copyright © 2016年 dengwei. All rights reserved.
//

import UIKit
import AddressBook
import AddressBookUI

let ContactTableViewCellIdentifier = "UserCell"

class ViewController: UIViewController {

    var contacttableview :UITableView!
    var contactdataSource:NSMutableArray!
    var contact_sectionSource:Dictionary<String, NSMutableArray>! = Dictionary<String, NSMutableArray>()
    var contact_headerSource:NSMutableArray!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "通讯录"
        
        self.view.backgroundColor = UIColor.whiteColor()
        
        self.contacttableview = UITableView(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight))
        self.contacttableview.registerClass(UserCell.self, forCellReuseIdentifier: ContactTableViewCellIdentifier)
        self.contacttableview.separatorStyle              = .None
        self.contacttableview.allowsSelection             = true
        self.contacttableview.delegate = self
        self.contacttableview.dataSource = self
        self.contacttableview.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
        
        self.view.addSubview(self.contacttableview)
        
        self.contactdataSource = NSMutableArray()
        self.contact_headerSource = NSMutableArray()
        
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
            
            self.initData()
            
            dispatch_async(dispatch_get_main_queue(), {
                self.contacttableview.reloadData()
            })
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    
    func initData(){
        
        self.getSysContacts()
        self.contact_sectionSource["#"] = NSMutableArray()
        for i in 65...90 {
            let key = String(format: "%c", i)
            //            print(key)
            self.contact_sectionSource[key] = NSMutableArray()
            
            self.contact_headerSource.addObject(key)
        }
        self.sortArray()
    }
    
    
    func isPureInt(string:String!) ->Bool{
        let scan:NSScanner! = NSScanner(string: string)
        var result = 0
        return scan.scanInteger(&result) && scan.atEnd
    }
    
    func sortArray(){
        for userModel in self.contactdataSource{
            
            var str:NSString! = NSString(UTF8String: (userModel as! UserModel).userName)
            
            if(str == ""){ continue }
            
            if str.containsString(" "){
                str = str.stringByReplacingOccurrencesOfString(" ", withString: "")
            }
            
            var key:String!
            
            key = String(format: "%c", pinyinFirstLetter(str.characterAtIndex(0))).uppercaseString
            
            if str.length <= 0 || isPureInt(key) || key == "_"{
                key = "#"
            }
            
            self.contact_sectionSource[key.uppercaseString]!.addObject(userModel as! UserModel)
        }
    }
    
    func getSysContacts() -> [[String:AnyObject]] {
        var error:Unmanaged<CFError>?
        var addressBook: ABAddressBookRef? = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()
        
        let sysAddressBookStatus = ABAddressBookGetAuthorizationStatus()
        
        if sysAddressBookStatus == .Denied || sysAddressBookStatus == .NotDetermined {
            // Need to ask for authorization
            var authorizedSingal:dispatch_semaphore_t = dispatch_semaphore_create(0)
            var askAuthorization:ABAddressBookRequestAccessCompletionHandler = { success, error in
                if success {
                    ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray
                    dispatch_semaphore_signal(authorizedSingal)
                }
            }
            ABAddressBookRequestAccessWithCompletion(addressBook, askAuthorization)
            dispatch_semaphore_wait(authorizedSingal, DISPATCH_TIME_FOREVER)
        }
        
        func analyzeSysContacts(sysContacts:NSArray) -> [[String:AnyObject]] {
            var allContacts:Array = [[String:AnyObject]]()
            
            func analyzeContactProperty(contact:ABRecordRef, property:ABPropertyID) -> [AnyObject]? {
                let propertyValues:ABMultiValueRef? = ABRecordCopyValue(contact, property)?.takeRetainedValue()
                if propertyValues != nil {
                    var values:Array<AnyObject> = Array()
                    for i in 0 ..< ABMultiValueGetCount(propertyValues) {
                        let value = ABMultiValueCopyValueAtIndex(propertyValues, i)
                        switch property {
                            // 地址
                        case kABPersonAddressProperty :
                            var valueDictionary:Dictionary = [String:String]()
                            
                            let addrNSDict:NSMutableDictionary = value.takeRetainedValue() as! NSMutableDictionary
                            valueDictionary["_Country"] = addrNSDict.valueForKey(kABPersonAddressCountryKey as String) as? String
                            valueDictionary["_State"] = addrNSDict.valueForKey(kABPersonAddressStateKey as String) as? String
                            valueDictionary["_City"] = addrNSDict.valueForKey(kABPersonAddressCityKey as String) as? String
                            valueDictionary["_Street"] = addrNSDict.valueForKey(kABPersonAddressStreetKey as String) as? String
                            valueDictionary["_Contrycode"] = addrNSDict.valueForKey(kABPersonAddressCountryCodeKey as String) as? String
                            
                            // 地址整理
                            //                            var fullAddress:String = (valueDictionary["_Country"]! == "" ? valueDictionary["_Contrycode"]! : valueDictionary["_Country"]!) + ", " + valueDictionary["_State"]! + ", " + valueDictionary["_City"]! + ", " + valueDictionary["_Street"]!
                            let fullAddress:String = ""
                            values.append(fullAddress)
                            
                            // SNS
                        case kABPersonSocialProfileProperty :
                            var valueDictionary:Dictionary = [String:String]()
                            
                            let snsNSDict:NSMutableDictionary = value.takeRetainedValue() as! NSMutableDictionary
                            valueDictionary["_Username"] = snsNSDict.valueForKey(kABPersonSocialProfileUsernameKey as String) as? String
                            valueDictionary["_URL"] = snsNSDict.valueForKey(kABPersonSocialProfileURLKey as String) as? String
                            valueDictionary["_Serves"] = snsNSDict.valueForKey(kABPersonSocialProfileServiceKey as String) as? String
                            
                            values.append(valueDictionary)
                            // IM
                        case kABPersonInstantMessageProperty :
                            var valueDictionary:Dictionary = [String:String]()
                            
                            let imNSDict:NSMutableDictionary = value.takeRetainedValue() as! NSMutableDictionary
                            
                            valueDictionary["_Username"] = imNSDict.valueForKey(kABPersonInstantMessageUsernameKey as String) as? String
                            valueDictionary["_Serves"] = imNSDict.valueForKey(kABPersonInstantMessageServiceKey as String) as? String
                            
                            values.append(valueDictionary)
                            // Date
                        case kABPersonDateProperty :
                            let date:String? = (value.takeRetainedValue() as? NSDate)?.description
                            if date != nil {
                                values.append(date!)
                            }
                        default :
                            let val:String = value.takeRetainedValue() as? String ?? ""
                            values.append(val)
                        }
                    }
                    return values
                }else{
                    return nil
                }
            }
            
            for contact in sysContacts {
                var currentContact:Dictionary = [String:AnyObject]()
                /*
                部分单值属性
                */
                // 姓、姓氏拼音
                let FirstName:String = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?.takeRetainedValue() as! String? ?? ""
                currentContact["FirstName"] = FirstName
                currentContact["FirstNamePhonetic"] = ABRecordCopyValue(contact, kABPersonFirstNamePhoneticProperty)?.takeRetainedValue() as! String? ?? ""
                // 名、名字拼音
                let LastName:String = ABRecordCopyValue(contact, kABPersonLastNameProperty)?.takeRetainedValue() as! String? ?? ""
                currentContact["LastName"] = LastName
                currentContact["LirstNamePhonetic"] = ABRecordCopyValue(contact, kABPersonLastNamePhoneticProperty)?.takeRetainedValue() as! String? ?? ""
                // 昵称
                currentContact["Nikename"] = ABRecordCopyValue(contact, kABPersonNicknameProperty)?.takeRetainedValue() as! String? ?? ""
                
                // 姓名整理
                currentContact["fullName"] = LastName + FirstName
                
                // 公司（组织）
                currentContact["Organization"] = ABRecordCopyValue(contact, kABPersonOrganizationProperty)?.takeRetainedValue() as! String? ?? ""
                // 职位
                currentContact["JobTitle"] = ABRecordCopyValue(contact, kABPersonJobTitleProperty)?.takeRetainedValue() as! String? ?? ""
                // 部门
                currentContact["Department"] = ABRecordCopyValue(contact, kABPersonDepartmentProperty)?.takeRetainedValue() as! String? ?? ""
                // 备注
                currentContact["Note"] = ABRecordCopyValue(contact, kABPersonNoteProperty)?.takeRetainedValue() as! String? ?? ""
                // 生日（类型转换有问题，不可用）
                //currentContact["Brithday"] = ((ABRecordCopyValue(contact, kABPersonBirthdayProperty)?.takeRetainedValue()) as NSDate).description
                
                /*
                部分多值属性
                */
                // 电话
                let Phone:Array<AnyObject>? = analyzeContactProperty(contact, property: kABPersonPhoneProperty)
                if Phone != nil {
                    currentContact["Phone"] = Phone
                }
                // print("phone     =     \(Phone)")
                // 地址
                let Address:Array<AnyObject>? = analyzeContactProperty(contact, property: kABPersonAddressProperty)
                if Address != nil {
                    currentContact["Address"] = Address
                }
                
                // E-mail
                let Email:Array<AnyObject>? = analyzeContactProperty(contact, property: kABPersonEmailProperty)
                if Email != nil {
                    currentContact["Email"] = Email
                }
                // 纪念日
                let Date:Array<AnyObject>? = analyzeContactProperty(contact, property: kABPersonDateProperty)
                if Date != nil {
                    currentContact["Date"] = Date
                }
                // URL
                let URL:Array<AnyObject>? = analyzeContactProperty(contact, property: kABPersonURLProperty)
                if URL != nil{
                    currentContact["URL"] = URL
                }
                // SNS
                let SNS:Array<AnyObject>? = analyzeContactProperty(contact, property: kABPersonSocialProfileProperty)
                if SNS != nil {
                    currentContact["SNS"] = SNS
                }
                allContacts.append(currentContact)
                if Phone != nil
                {
                    let count = (Phone!.count-1) as Int
                    
                    let firstName = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?.takeRetainedValue()  as! String? ?? ""
                    let lastName = ABRecordCopyValue(contact, kABPersonLastNameProperty)?.takeRetainedValue()   as! String? ?? ""
                    
                    let userModel:UserModel! = UserModel()
                    userModel.userId = "0000000"
                    userModel.userName = lastName + firstName
                    userModel.userAvator = ""
                    userModel.userStatus = 1
                    userModel.userMobile = Phone![0] as! String
                    
                    self.contactdataSource.addObject(userModel)
                    
                }
            }
            return allContacts
        }
        return analyzeSysContacts(ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray )
    }


}


extension ViewController: UITableViewDelegate, UITableViewDataSource{
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        
        return self.contact_headerSource.count
    }
    
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        
        return self.contact_headerSource.objectAtIndex(section) as? String
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.contact_sectionSource[self.contact_headerSource.objectAtIndex(section) as! String]!.count
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if(self.contact_sectionSource[self.contact_headerSource.objectAtIndex(section) as! String]!.count <= 0){
            return 0
        }
        
        return 25
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(ContactTableViewCellIdentifier, forIndexPath: indexPath) as! UserCell
        
        let sectionData = self.contact_sectionSource[self.contact_headerSource.objectAtIndex(indexPath.section) as! String]
        
        let user:UserModel! = sectionData?.objectAtIndex(indexPath.row) as! UserModel
        
        cell.configContact(user, contactViewController: self)
        
        if(indexPath.row % 3 == 0){
            cell.backgroundColor = UIColor(red: 254/255.0, green: 214/255.0, blue: 49/255.0, alpha: 1.0)
        }else if(indexPath.row  % 3 == 1){
            cell.backgroundColor = UIColor(red: 253/255.0, green: 173/255.0, blue: 43/255.0, alpha: 1.0)
        }else if(indexPath.row  % 3 == 2){
            cell.backgroundColor = UIColor(red: 254/255.0, green: 139/255.0, blue: 46/255.0, alpha: 1.0)
        }
        
        return cell;
    }
    
    func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
        let a1 = self.contact_headerSource
        let nsArray: NSArray = a1
        let objArray: [AnyObject] = nsArray as Array //as Array会转换为AnyObject数组
        let strArray: [String] = objArray as! [String]
        return strArray
    }
    
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let sectionData = self.contact_sectionSource[self.contact_headerSource.objectAtIndex(indexPath.section) as! String]
        
        let user:UserModel! = sectionData?.objectAtIndex(indexPath.row) as! UserModel
        let name = user.userName
        let mobile = user.userMobile
        
        print("name=\(name),mobile=\(mobile)")
    }
    
}
